//
//  HJCPhotoViewController.swift
//  新浪微博Swift
//
//  Created by 郝俊聪 on 15/5/19.
//  Copyright (c) 2015年 heima. All rights reserved.
//

import UIKit
import SDWebImage
import SVProgressHUD

class HJCPhotoViewController: UIViewController,UIScrollViewDelegate {
    
    var scale : CGFloat = 1.0
    
    weak var fatherView : UIView?
    
     var comletion : (()->())?
    
    var imageURL : String?{
        didSet{
//            
            if imageURL != nil{
                let url = NSURL(string: imageURL!)
                //先去缓存取
                if  let cacheImage = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(imageURL){
                    self.setImageAndScrollView(cacheImage)
                    return
                }
                //下载图片
                SVProgressHUD.show()
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: nil, progress: { (_, _) -> Void in
                    
                }, completed: { (image, error, _, _, _) -> Void in
                    if error != nil || image == nil{
                       SVProgressHUD.showErrorWithStatus("图片下载失败")
                    }else{
                        self.setImageAndScrollView(image)
                    }
                    SVProgressHUD.dismiss()
                })
            }
        
        }
    }
    
    var dummyView : UIView?
    
    ///判断长图短图
    func setImageAndScrollView(image:UIImage){
        
         let size = scaleImageSize(image)
        
         photoView.image = image
        
         photoView.frame = CGRectMake(0, 0, size.width, size.height)
        
         //判断是长图还是短图
        let sh = view.bounds.height
        if size.height > sh{
            scrollView.contentSize = size
        }else{
//            scrollView.contentSize = UIScreen.mainScreen().bounds.size
            let top = (sh - size.height)*0.5
//            photoView.frame = CGRectMake(0, y, size.width, size.height)
            scrollView.contentInset = UIEdgeInsetsMake(top, 0, 0, 0)
//            println(photoView.frame)
//            println(scrollView.contentInset.top)
//            println(scrollView.frame)
        }
        
    
    }
    
    ///缩放图片的大小
    func scaleImageSize(image:UIImage)->CGSize{
        //缩放后的宽度是
        let sw = view.bounds.width
        //高度是
        let sh = sw*(image.size.height/image.size.width)
        
        return CGSize(width: view.bounds.width, height: sh)

    }

    lazy var photoView : UIImageView = {
        let imageView = UIImageView()
        imageView.backgroundColor = UIColor.whiteColor()
        imageView.userInteractionEnabled = true
        return imageView
    
    }()
    
    lazy var scrollView : UIScrollView = {
       let  sv = UIScrollView()
        sv.frame = self.view.bounds
       sv.delegate = self
       sv.minimumZoomScale = 0.5
       sv.maximumZoomScale = 2
       return sv
    }()
    
    override func loadView() {
        super.loadView()
        view.addSubview(scrollView)
        scrollView.addSubview(photoView)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }
    
   ///布局完成之后重新设置图片的大小
   override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    
//    scrollView.frame = self.view.bounds

   }
    
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return photoView
    }
    
    
    func scrollViewDidZoom(scrollView: UIScrollView) {
        scale = scrollView.zoomScale
        
        if scale < 1{
           startInteractiveTransition(self)
        }
    }
    
    //结束滚动的时候
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView!, atScale scale: CGFloat) {
        
        if scale < 1 {
            
            
            //通知转场
            comletion!()
                
            
            return
        }
        
        //放大的时候，重新计算scrollView的上边距
        let top = (scrollView.frame.size.height - view.frame.size.height)*0.5
        if top > 0{
            
            scrollView.contentInset = UIEdgeInsetsMake(top, 0, 0, 0)
        }else{
            scrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0)
        }
        
        
    }
    
}


///交互转场代理
extension HJCPhotoViewController : UIViewControllerInteractiveTransitioning{
    
    func startInteractiveTransition(transitionContext: UIViewControllerContextTransitioning){
        
        
        let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)
        let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewKey)
        let toView = toVC?.view
//        println("111"+"\(toVC)")
//        println("222"+"\(fromVC)")
        
//        dummyView = toView!.snapshotViewAfterScreenUpdates(false)
        
//        transitionContext.containerView().insertSubview(dummyView!, belowSubview: view!)
        
        view.transform = CGAffineTransformMakeScale(scale, scale)

        fatherView?.alpha = scale
        
        
    }


}

///转场
extension HJCPhotoViewController : UIViewControllerContextTransitioning{
    func containerView() -> UIView{
         return self.view.superview!
    }
    
    func viewForKey(key: String) -> UIView? {
        if key == UITransitionContextToViewKey{
            return UIApplication.sharedApplication().keyWindow!.rootViewController!.view
        }else{
            return self.view
        }
    }
    
    func isAnimated() -> Bool{
        return true
    }
    
    func isInteractive() -> Bool{
        return true
    }
    
    func transitionWasCancelled() -> Bool{
        return false
    }
    
    func presentationStyle() -> UIModalPresentationStyle{
       return UIModalPresentationStyle.Custom
    }
  
    func updateInteractiveTransition(percentComplete: CGFloat){
        
    }
    func finishInteractiveTransition(){
        
    }
    func cancelInteractiveTransition(){
    }
    
    
    func completeTransition(didComplete: Bool){
        dismissViewControllerAnimated(true, completion: { () -> Void in
            
        })
        
    }
    func viewControllerForKey(key: String) -> UIViewController?{
    
        if key == UITransitionContextToViewControllerKey {
            // rootViewController －> MainTabBarController
            return UIApplication.sharedApplication().keyWindow!.rootViewController
            // childViewControllers[0] as! UINavigationController).topViewController
        } else {
            return self
        }
    }
    
    
   
    
    @availability(iOS, introduced=8.0)
    func targetTransform() -> CGAffineTransform{
        
        return CGAffineTransformIdentity
    }
    
    func initialFrameForViewController(vc: UIViewController) -> CGRect{
        
        return CGRectZero
    
    }
    func finalFrameForViewController(vc: UIViewController) -> CGRect{
        return CGRectZero
    }



}
